/*
 * @Descripttion: axios封装
 * @Date: 2021-12-17 09:33:09
 * @LastEditTime: 2021-12-17 10:24:32
 */
import axios from 'axios'
import { Message, MessageBox } from 'element-ui'

const token = 'xxxxx'

// 创建axios实例
const service = axios.create({
  timeout: 5000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  config.token = token
  return config
})

// response拦截器
const STATUS_CODE = {
  SUCCESS: 200,
  NOT_FOUND: 404,
  SERVER_ERROR: 500,
  LOG_OUT: 401
}
service.interceptors.response.use(
  response => {
    const res = response.data

    if (res.status !== STATUS_CODE.SUCCESS) {
      Message.error(res.message || '网络错误')
      if (res.status === STATUS_CODE.LOG_OUT) {
        MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          location.reload()
        })
      }
      return Promise.reject(new Error(res.message || '网络错误'))
    } else {
      return res
    }
  },
  error => {
    Message.error(error.message)
    return Promise.reject(error)
  }
)

export default service
